#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<wait.h>

void writer(int wfd)
{
  char buffer[124];
  const char* str="hello father,Im child";
  pid_t id=getpid();
  int cnt=0;
  while(1)
  {
    snprintf(buffer,sizeof(buffer),"message: %s, pid: %d, count: %d\n",str,id,cnt);
    write(wfd,buffer,strlen(buffer));
    cnt++;
    sleep(1);
  }
}

void reader(int rfd)
{
  char buffer[1024];
  while(1)
  {
    ssize_t n=read(rfd,buffer,sizeof(buffer)-1);
    (void)n;
    printf("father get a message:%s",buffer);

  }
}
int main()
{
  int pipefd[2];
  int n=pipe(pipefd);
  if(n<0) return 1;
  printf("pipefd[0]:%d, pipefd[1]:%d\n",pipefd[0],pipefd[1]);//3 4

  pid_t id=fork();
  //子进程 写
  if(id==0)
  {
    close(pipefd[0]);
    writer(pipefd[1]);
    exit(0);
  }
  //父进程 读
  close(pipefd[1]);
  reader(pipefd[0]);
  wait(NULL);
  return 0;
}
